package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.config.RabbitConfig;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@Component
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${file.oss.web-site}")
    String webSite;
    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    WmMaterialMapper wmMaterialMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 查询所有自媒体文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        //1.参数检查
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //2.条件封装执行查询
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        //2.1文本标题模糊查询
        wrapper.like(StringUtils.isNotBlank(dto.getKeyword()), WmNews::getTitle, dto.getKeyword());
        //2.2 频道id
        wrapper.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        //2.3文章状态
        wrapper.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        //2.4发布时间==>开始时间
        wrapper.ge(dto.getBeginPubDate() != null, WmNews::getCreatedTime, dto.getBeginPubDate());
        //2.5发布时间<==开始时间
        wrapper.le(dto.getEndPubDate() != null, WmNews::getPublishTime, dto.getEndPubDate());
        //2.6当前自媒体人文章
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        wrapper.eq(WmNews::getUserId, user.getId());
        //2.7按照创建日期排序
        wrapper.orderByDesc(WmNews::getCreatedTime);
        //2.8分页查询构建
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        //3.执行查询
        IPage<WmNews> pageResult = page(page, wrapper);
        //4.返回封装查询结果
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal());
        result.setData(pageResult.getRecords());
        //4.1处理文章图片
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
        //1.检查参数 封装WmNews对象
        WmNews wmNews = parseDtoToWmNews(dto);
        //2.保存或修改
        saveOrUpdateWmNews(wmNews);
        //3.1关联抽取文章中关联的图片路径
        List<String> materiaUrls = parseContentImages(wmNews.getContent());
        //3.2关联抽取文章中关联图片和素材关系
        saveRelativeInfo(materiaUrls, wmNews, WemediaConstants.WM_CONTENT_REFERENCE);
        //3.3关联抽取文章中关联图片和素材关系, 封面是可能选择自动或无图
        saveRelativeInfoForCover(materiaUrls, wmNews, dto);
        //4.发送mq信息 ,触发异步自动审核
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        log.info("成功发送文章自动审核信息 目的队列:{}  文章id:{}", NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        return ResponseResult.okResult();
    }

    /**
     * 自媒体文章-根据id查询
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1.参数检查
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.执行查询
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult delNews(Integer id) {
        //1.检查参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章的id是不可缺少");
        }
        //2.获取数据
        WmNews wmNews = getById(id);
        //3.判断当前文章的状态
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode()) && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已发布,不能删除");
        }
        //4.去除文章与素材的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //1.检查参数
        if (dto==null||dto.getId()==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable = dto.getEnable();
        if (enable==null||( !WemediaConstants.WM_NEWS_UP.equals(enable)&&!WemediaConstants.WM_NEWS_DOWN.equals(enable))) {
        CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"上下架状态错误");
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断文章是否发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态,不能上下架");
        }
        //4.修改文章状态,同步到app端
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId()).set(WmNews::getEnable,dto.getEnable()));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     *关联抽取文章中关联图片和素材关系, 封面是可能选择自动或无图
     */
    private void saveRelativeInfoForCover(List<String> materiaUrls, WmNews wmNews, WmNewsDTO dto) {
        List<String> images = dto.getImages();
        //判断前端传入type是否为-1
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            //需要自动生成封面 规则
            int size = materiaUrls.size();
            if (size == 0) {
                //内容中没有图片 则为无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            } else if (size <= 2) {
                //从素材中截取一张图片赋值给images
                images = materiaUrls.stream().limit(1).collect(Collectors.toList());
                //内容图片得到个数小于等于2.则为单图截图一张图
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            } else {
                images = materiaUrls.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            }
            if (!CollectionUtils.isEmpty(images)) {
                wmNews.setImages(imageToStr(images));
            }
            this.updateById(wmNews);
        }
        if (!CollectionUtils.isEmpty(images)) {
            images = images.stream().map(url -> url.replaceAll(webSite, "")).collect(Collectors.toList());
        }
        if (!CollectionUtils.isEmpty(images)) {
            images = images.stream().map(url -> url.replaceAll(webSite, "")).collect(Collectors.toList());
            //调用保存关联关系方法
            saveRelativeInfo(images, wmNews, WemediaConstants.WM_IMAGE_REFERENCE);
        }

    }

    /**
     * 保存素材和文章关联关系方法
     *
     * @param materiaUrls 素材的路径List
     * @param wmNews      文章
     * @param type        引用类型 0 内容引用 1 封面引用
     */
    private void saveRelativeInfo(List<String> materiaUrls, WmNews wmNews, Short type) {
        //1.先根据素材路径集合  查询素材库 得到对应的id集合
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
                .in(WmMaterial::getUrl, materiaUrls)
                //只返回id字段
                .select(WmMaterial::getId)
        );
        //2.判断id集合的数量是否等于素材路径集合的数量 不等于提示素材缺失
        if (wmMaterials.size() < materiaUrls.size()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "素材丢失");
        }
        //3.批量插入关联关系
        for (WmMaterial wmMaterial : wmMaterials) {
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setMaterialId(wmMaterial.getId());
            wmNewsMaterial.setNewsId(wmNews.getId());
            wmNewsMaterial.setType(type);
            wmNewsMaterialMapper.insert(wmNewsMaterial);
        }
    }

    /**
     * 提取出内容中 所涉及的素材路径
     *
     * @param content
     * @return
     */
    private List<String> parseContentImages(String content) {
        List<Map> maps = JSON.parseArray(content, Map.class);
        return maps.stream()//创建流
                //集合中 找到所有type 为image 的map
                .filter(x -> "image".equals(x.get("type")))
                //获取mao的value字段值 得到路径
                .map(x -> String.valueOf(x.get("value")))
                //替换掉路径的前缀
                .map(url -> url.replaceAll(webSite, ""))
                //去除重复的素材
                .distinct()
                //将得到的素材返回路径集合
                .collect(Collectors.toList());
    }

    /**
     * 保存或修改文章 文章对象(前端传递)
     *
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        wmNews.setCreatedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);//上架
        if (wmNews.getId() == null) {//保存操作
            save(wmNews);
        } else { //修改
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        }
    }

    private WmNews parseDtoToWmNews(WmNewsDTO dto) {
        //1.参数校验
        if (StringUtils.isBlank(dto.getContent())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章的标题不能为空");
        }
        //1.1检验是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "请先登录");
        }
        //2.保存或修改文章
        WmNews wmNews = new WmNews();
        //2.1将dto参数里面的值设置到wmNews
        BeanUtils.copyProperties(dto, wmNews);
        //2.2如果文章布局时自动的,需要设置为null
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        //2.3处理 dto参数imags封面集合转换为字符串
        if (!CollectionUtils.isEmpty(dto.getImages())) {
            wmNews.setImages(imageToStr(dto.getImages()));
        }
        //补全id
        wmNews.setUserId(user.getId());
        return wmNews;
    }

    /**
     * 将字符转成字符串用,拼接
     *
     * @param images [url1.jpg,url2.jpg]
     * @return
     */
    private String imageToStr(List<String> images) {
        return images.stream() //创建流对象
                //替换路径中的访问前缀
                .map(url -> url.replaceAll(webSite, ""))
                //将字符串使用逗号拼接
                .collect(Collectors.joining(","));
    }
    @Autowired
    WmNewsMapper wmNewsMapper;
    /**
     * 查询文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        //1.检查参数
        dto.checkParam();
        //记录当前页
        int currentPage = dto.getPage();
        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());

        if(StringUtils.isNotBlank(dto.getTitle())){
            //  concat(%,?,%)
            dto.setTitle("%"+dto.getTitle()+"%");
        }

        //2.分页查询
        List<WmNewsVO> wmNewsVoList = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        long count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        ResponseResult result = new PageResponseResult(currentPage, dto.getSize(), count, wmNewsVoList);
        result.setHost(webSite);
        return result;
    }
    @Autowired
    WmUserMapper wmUserMapper;
    /**
     * 查询文章详情
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1参数检查
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询作者
        WmUser wmUser = null;
        if(wmNews.getUserId() != null){
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }

        //4.封装vo信息返回
        WmNewsVO wmNewsVo = new WmNewsVO();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser != null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(webSite);
        return responseResult;
    }

    /**
     * 自媒体文章人工审核
     * @param status 2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        //1.参数检查
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 检查文章状态 不能为9  已发布
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章已发布");
        }
        //3.修改文章状态
        wmNews.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);

        // TODO 通知定时发布文章
        if (WemediaConstants.WM_NEWS_AUTH_PASS.equals(status)){
            //1.获取发布时间
            long publishTime = wmNews.getPublishTime().getTime();
            //2.获取当前时间
            long nowTime = System.currentTimeMillis();
            //3.距离发布时间=发布时间-当前时间
            long remainTime = publishTime - nowTime;
            //4.发送消息,并设置消息头 x-delay: 距离发布时间
            rabbitTemplate.convertAndSend(
                    PublishArticleConstants.DELAY_DIRECT_EXCHANGE,
                    PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY,
                    wmNews.getId(),
                    new MessagePostProcessor() {
                        /**
                         * 消息后置处理器用于改变消息属性
                         * @param message
                         * @return
                         * @throws AmqpException
                         */
                        @Override
                        public Message postProcessMessage(Message message) throws AmqpException {
                            message.getMessageProperties()
                                    .setHeader("x-delay", remainTime <= 0 ? 0 : remainTime);
                            return message;
                        }
                    }
            );
            log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());
        }


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
